from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from apps.home_page.models import UdwUser, UdwUserInfo, UdwUserSite
from alipay import AliPay
import os
from udw_shopping import settings
from django.http import JsonResponse
import requests
from util import aliyun
from django.core.cache import cache
from util import restful
#我的X袋
class Udai_welcome(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_welcome.html', {'username': phone})

    def post(self, request):
        pass


#个人资料
class Udai_setting(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=id)
            userinfo = UdwUserInfo.objects.get(user_id=id)
            birthday = userinfo.birthday.strftime('%F')
        return render(request, 'udai_setting.html', {'user': user,
                                                     'username': user.user_phone,
                                                     'user_info': userinfo,
                                                     'birthday': birthday})

    def post(self, request):
        id = request.session.get('id')
        username = request.POST.get('username')
        sex = request.POST.get('sex')
        birthday = request.POST.get('birthday')
        user_info = UdwUserInfo.objects.get(user_id=id)
        user_info.name = username
        user_info.sex = sex
        user_info.birthday = birthday
        user_info.save()
        return render(request, 'inform.html', {'message': '修改成功'})





#资金管理
class Udai_treasurer(View):
    def get(self, request):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=user_id)
            return render(request, 'udai_treasurer.html', {'username': user.user_phone,
                                                           'user': user})
    def post(self, request):
        pass

#支付宝支付
class ZFB_Pay(View):
    def post(self, request):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        money = request.POST.get('money')
        pay_method = request.POST.get('pay_method')
        print(money)
        print(pay_method)
        if pay_method == 'Alipay':
            alipay = AliPay(
                    appid="2016101400683190",
                    app_notify_url=None,  # 默认回调url
                    app_private_key_path=os.path.join(settings.BASE_DIR, 'util/aly/app_private_key.pem'),
                    # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
                    alipay_public_key_path=os.path.join(settings.BASE_DIR, 'util/aly/alipay_pubilc_key.pem'),
                    sign_type="RSA2",   # RSA 或者 RSA2
                    debug=True,    #默认False
                )
            order_string = alipay.api_alipay_trade_page_pay(
                    out_trade_no='123456',
                    total_amount=money,
                    subject="U袋网用户余额充值",
                    return_url="http://127.0.0.1:8000/order_from/udai_treasurer/",
                )
            # 构造用户跳转的支付链接地址
            pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(order_string)
            # res = requests.get(pay_url)
            return redirect(pay_url)
        else:
            return HttpResponse('haha')




    #积分平台
class Udai_integral(View):
    def get(self, request):
        return render(request, 'udai_integral.html')

    def post(self, request):
        pass


#收货地址
class Udai_address(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            return render(request, 'udai_address.html')
        # else:
            # default_site = None
            # user = UdwUser.objects.get(user_id=id)
            # try:
            #     default_site = UserSite.objects.get(user_id=id, default='1')
            # except UserSite.DoesNotExist:
            #     pass
            # sites = UserSite.objects.filter(user_id=id, default='0')
            # return render(request, 'udai_address.html', {'username': user.user_phone,
            #                                              'd_site': default_site,
            #                                              'sites': sites})
    def post(self, request):
        pass



#修改已经保存的收货地址
class Udai_address_edit(View):
    def get(self, request):
        return render(request, 'udai_address_edit.html')

    def post(self, request):
        pass

#我的优惠卷
class Udai_coupon(View):
    def get(self, request):
        return render(request, 'udai_coupon.html')

    def post(self, request):
        pass

#修改支付密码
class Udai_paypwd_modify(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_paypwd_modify.html', {'username': phone})

    def post(self, request):
        pass




#修改支付密码2
class Udai_modifypay_step(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypay_step1.html', {'username': phone})

    def post(self, request):
        id = request.session.get('id')
        phone = request.POST.get('phone')
        code = request.POST.get('sms')
        code2 = cache.get(phone)
        if code == code2:
            return redirect('account_info:udai_modifypay_step2')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypay_step1.html', {'username': phone})

#修改支付密码2
class Udai_modifypay_step2(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypay_step2.html', {'username': phone})

    def post(self, request):
        id = request.session.get('id')
        user = UdwUser.objects.get(user_id=id)
        password = request.POST.get('phone')
        password2 = request.POST.get('phone2')
        if password != password2:
            return render(request, 'udai_modifypay_step2.html', {'username': user.user_phone, 'error': '2次密码不一致'})
        if len(password) != 6:
            return render(request, 'udai_modifypay_step2.html', {'username': user.user_phone, 'error': '密码只能为6位'})
        user.payment_code = password
        user.save()
        return redirect('account_info:udai_modifypay_step3')


#修改支付密码3
class Udai_modifypay_step3(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypay_step3.html', {'username': phone})

    def post(self, request):
        pass


def sms_send(request):
    phone = request.GET.get('phone')
    code = aliyun.get_code()
    cache.set(phone, code, 6000)
    #判断缓存中是否有phone
    cache.has_key(phone)
    #获取redis验证码
    cache.get(phone)
    result = aliyun.send_sms(phone, code)
    return HttpResponse(result)



#短信验证码验证接口
def sms_check(request):
    # 1.获取电话和手动输入的验证码
    phone = request.GET.get('phone')
    print(phone)
    code = request.GET.get('sms')
    print(code)
    # 要先定义一个假的，要不然直接就是None,如果没有获取到redis里存储的验证码，也会是None,到时就会皮队成功
    cache_code = "1"
    #2.获取redis中保持的code
    if cache.has_key(phone):   #判断缓存中是否包含 phone 键
        # 获取redis验证码
        cache_code = cache.get(phone)
        print(cache_code)
    # 3.判断返回数据
    if code == cache_code:
        # return HttpResponse(json.dumps({"result": 'True'}))
        return restful.ok("ok", data=None)
    else:
        # return HttpResponse(json.dumps({"result": 'False'}))
        return restful.params_error("验证码错误", data=None)



















#修改登录密码
class Udai_pwd_modify(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_pwd_modify.html', {'username': phone})

    def post(self, request):
        pass

# 修改登录密码1
class Udai_modifypwd_step1(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypwd_step1.html', {'username': phone})

    def post(self, request):
        id = request.session.get('id')
        password = request.POST.get('password')
        if UdwUser.objects.get(user_id=id).user_password == password:
            return redirect('account_info:udai_modifypwd_step2')
        id = request.session.get('id')
        phone = UdwUser.objects.get(user_id=id).user_phone
        return render(request, 'udai_modifypwd_step1.html', {'username': phone, 'error':'和原密码不一致,重新输入'})



# 修改登录密码2
class Udai_modifypwd_step2(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypwd_step2.html', {'username': phone})

    def post(self, request):
        id = request.session.get('id')
        user = UdwUser.objects.get(user_id=id)
        pwd = request.POST.get('password')
        pwd2 = request.POST.get('password2')
        if not all([pwd, pwd2]):
            return render(request, 'udai_modifypwd_step2.html', {'username': user.user_phone, 'error': '信息不完整'})
        if pwd != pwd2:
            return render(request, 'udai_modifypwd_step2.html', {'username': user.user_phone, 'error': '2次密码输入不一致'})
        if 6 > len(pwd):
            return render(request, 'udai_modifypwd_step2.html', {'username': user.user_phone, 'error': '密码小于6位'})
        if len(pwd) > 16:
            return render(request, 'udai_modifypwd_step2.html', {'username': user.user_phone, 'error': '密码大于16位'})
        user.user_password = pwd
        user.save()
        request.session.flush()
        return redirect('account_info:udai_modifypwd_step3')

# 修改登录密码3
class Udai_modifypwd_step3(View):
    def get(self, request):
        id = request.session.get('id')
        if not id:
            return redirect('login_register:login')
        else:
            phone = UdwUser.objects.get(user_id=id).user_phone
            return render(request, 'udai_modifypwd_step3.html', {'username': phone})

    def post(self, request):
        pass


